package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.aspectj.weaver.ast.Var;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //创建criteria
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        //查询总记录数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页参数
        query.skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询分页数据列表
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        //构造返回值
        return new PageResult(page, pagesize, count, movements);

    }

    @Override
    public void publish(Movement movement) {
        //1、保存动态详情
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //保存数据
            mongoTemplate.save(movement);
            //2、查询当前用户的好友数据
            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
            Query query = Query.query(criteria);
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            //3、循环好友数据，构建时间线数据存入数据库
            for (Friend friend : friends) {
                MovementTimeLine timeLine = new MovementTimeLine();
                timeLine.setMovementId(movement.getId());
                timeLine.setUserId(friend.getUserId());
                timeLine.setFriendId(friend.getFriendId());
                timeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.save(timeLine);
            }
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    //查询好友
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //1、根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        //movementTimeLines为可以看动态的好友对象集合
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id列表
        List<ObjectId> movementIdlist = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //3：根据movementId查询动态对象
        Query movementQuery = Query.query(Criteria.where("id").in(movementIdlist));
        List<Movement> movements = mongoTemplate.find(movementQuery, Movement.class);
        return movements;
    }

    @Override
    public List<Movement> randomMovements(Integer counts) {
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //2、调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3、获取统计结果
        return results.getMappedResults();

    }

    @Override
    public Movement findBymovementId(String movementId) {
        Movement byId = mongoTemplate.findById(movementId, Movement.class);
        return byId;
    }

    @Override
    public PageResult findFriendMovement(Integer page, Integer pagesize, Long uid, Integer state) {
        Query query = new Query();
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.limit(pagesize).skip((page - 1) * pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,movementList);
    }
}
